package com.zyh.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisUtils {
    private static Jedis jedis = null;
    static {
        Properties properties = new Properties();
        InputStream resourceAsStream = JedisUtils.class.getResourceAsStream("/redis.properties");
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JedisPoolConfig config = new JedisPoolConfig();
        //从连接池获取连接时，是否检测连接的有效性
        String testOnBorrow = properties.getProperty("redis.testOnBorrow");
        boolean boo = Boolean.parseBoolean(testOnBorrow);
        config.setTestOnBorrow(boo);
        //可用连接实例的最大数目，默认值为8
        String maxTotal = properties.getProperty("redis.maxTotal");
        Integer maxTotalInt = Integer.parseInt(maxTotal);
        config.setMaxTotal(maxTotalInt);
        //最大空闲连接数, 默认8个
        String maxIdle = properties.getProperty("redis.maxIdle");
        Integer maxIdleInt = Integer.parseInt(maxIdle);
        config.setMaxIdle(maxIdleInt);
        //最小空闲连接数，默认8个
        String mixIdle = properties.getProperty("redis.minIdle");
        Integer mixIdleInt = Integer.parseInt(mixIdle);
        config.setMinIdle(mixIdleInt);
        //没有空闲连接时，最大的等待毫秒数
        String maxWaitMillis = properties.getProperty("redis.maxWaitMillis");
        Integer maxWaitMillisInt = Integer.parseInt(maxWaitMillis);
        config.setMaxWaitMillis(maxWaitMillisInt);
        //创建连接池
        String hostName = properties.getProperty("redis.hostName");
        String port = properties.getProperty("redis.port");
        Integer portInt = Integer.parseInt(port);
        JedisPool pool = new JedisPool(config,hostName,portInt);
        //获取连接
        jedis = pool.getResource();
    }
    public static Jedis getJedis(){
        return jedis;
    }
}
